/**
 * 设置表单值
 * @param el
 * @param data
 */
function setFromValues(el, data) {
    for (var p in data) {
        el.find(":input[name='" + p + "']").val(data[p]);
    }
}
function setTdValues(el, data) {
	for(var p in data) {
		el.find("td[name='" + p + "']").text(data[p]);
	}
}
var treeViewHelper = {};
/**
 * tree view遍历节点值
 * @param node
 * @returns {Array}
 */
treeViewHelper.getChildrenNodeIdArr = function ( node ){
    var ts = [];
    if(node.nodes){
        for(x in node.nodes){
            ts.push(node.nodes[x].nodeId)
            if(node.nodes[x].nodes){
                var getNodeDieDai = this.getChildrenNodeIdArr(node.nodes[x]);
                for(j in getNodeDieDai){
                    ts.push(getNodeDieDai[j]);
                }
            }
        }
    }else{
        ts.push(node.nodeId);
    }
    return ts;
}
/**
 * 获取treeview的父级节点
 * @param treeId
 * @param node
 * @returns {Array}
 */
treeViewHelper.getParentIdArr = function (treeId,node){
    var ts = [];
    var parent  =   $('#'+treeId).treeview('getParent', node);
    while(parent.id&&parent.id!=0){
        ts.push(parent);
        parent = $('#'+treeId).treeview('getParent', parent);
    }
    return ts;
}
var tip = {
    alert: function (info, iconIndex) {
        layer.msg(info, {
            icon: iconIndex
        });
    }
} ;
$(function(){
    // 设置jQuery Ajax全局的参数
    $.ajaxSetup({
        //  type: "POST",
        error: function(jqXHR, textStatus, errorThrown){
            switch (jqXHR.status){
                case(500):
                    tip.alert("服务器系统内部错误",5);
                    break;
                case(401):
                    tip.alert("账号未登录或登录超时或在其他地方登录,请重新登录",5);
                    break;
                case(403):
                    tip.alert("无权限执行此操作",5);
                    break;
                case(408):
                    tip.alert("请求超时",5);
                    break;
                default:
                    tip.alert("未知错误",5);
            }
        },
        beforeSend:function(jqXHR,settings){ 
        	if(settings.type.toUpperCase()=='GET'){
        		settings.url=settings.url.indexOf("_=")!=-1?settings.url:(settings.url.indexOf('?')!=-1?(settings.url+'&_='+new Date().getTime()):(settings.url+'?_='+new Date().getTime()));
        	}
            layer.load(2, {shade: [0.6, '#fff']})
        },
        complete:function(xhr,status){
            layer.closeAll('loading');
        }
    });
});
//获取路径参数
getUrlParam = function(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return decodeURI(r[2]); return null;
};
//当前日期
var date=new Date();
var y=date.getFullYear();
var m=date.getMonth()+1;
var d=date.getDate();
var DD=date.getDay();
var newDate=y +"-" + m + "-" + d;
//日期+0
function geTime(i){
	if(i<=9){
		return '0'+i;
	}else{
		return i;
	}
};
var Io = {};
Io.on = function(obj, event, func){
	$(document).off(event, obj).on(event, obj, func);
};
Io.bs 	= {};
Io.bs.modaloptions = {
		url 	: '',
		fade	: 'fade',
		close	: true,
		title	: '弹窗',
		head	: true,
		foot	: true,
		btn		: false,
		okbtn	: '确定',
		qubtn	: '取消',
		msg		: 'msg',
		size	: false,
		show	: false,
		remote	: false,
		backdrop: false,
		keyboard: false,
		style	: '',
		mstyle	: ''
	};
	Io.bs.modalstr = function(opt){
		var start = '<div class="modal '+opt.fade+'" id="bsmodal" tabindex="-1" role="dialog" aria-labelledby="bsmodaltitle" aria-hidden="true" style="'+opt.style+'">';
		if(opt.size){
			start += '<div class="modal-dialog modal-'+opt.size+'" style="'+opt.mstyle+'"><div class="modal-content">';
		}else{
			start += '<div class="modal-dialog" style="'+opt.mstyle+'"><div class="modal-content">';
		}
		var end = '</div></div></div>';
		
		var head = '';
		if(opt.head){
			head += '<div class="modal-header">';
			if(opt.close){
				head += '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
			}
			head += '<h4 class="modal-title" id="bsmodaltitle">'+opt.title+'</h4></div>';
		}
		
		var body = '<div class="modal-body"><div class="tipMsg">'+opt.msg+'</div></div>';
		
		var foot = '';
		if(opt.foot){
			foot += '<div class="modal-footer"><button type="button" class="btn btn-primary bsok">'+opt.okbtn+'</button>';
			
			if(opt.qubtn){
				foot += '<button type="button" class="btn btn-default bscancel" data-dismiss="modal">'+opt.qubtn+'</button>';
			}
			foot += '</div>';
		}
		
		return start + head + body + foot + end;
	};
Io.bs.alert=function(options, func, func1){
	var opt=$.extend({},Io.bs.modaloptions);
	opt.title = '提示';
	if(typeof options=="string"){
		opt.msg=options;
	}else{
		$.extend(opt, options);
	}
	//append body
	$('body').append(Io.bs.modalstr(opt));
	var $modal = $('#bsmodal');
	$modal.modal(opt);
	//bind
	Io.on("button.bsok","click",function(){
		if(func) func();
		$modal.modal('hide');
	});
	$modal.on("hidden.bs.modal",function(){
		$modal.remove();
		$(".modal-backdrop").remove();
	});
	/*window.top.$('button.bscancel').on('click', function(){
		if(func1) func1();
		$modal.remove();
		window.top.$(".modal-backdrop").remove();
	});*/
	Io.on("button.bscancel","click",function(){
		if(func1) func1();
		$modal.remove();
		$(".modal-backdrop").remove();
	});
	//show
	$modal.modal('show');
};

//select枚举值选项
function selectOnload(settings){
	var defaultSetting = {
			json:{},//
			func:"",
			length:0,//json长度
			isDefault:true,//是否开启默认值
	};
	$.extend(defaultSetting,settings);
	var json = defaultSetting.json,
		func = defaultSetting.func,
		length = defaultSetting.length,
		isDefault = defaultSetting.isDefault;
	var n = 0;	
	for(var x in json){// id:val
		selectEva(x,json[x]);
	}
	function selectEva(id,val){	
		$.get("/admin/dic/"+val,null,function(data){
			if(data.code=='200'){
				n++;
				var ids=$("#"+id);
				if(data.data!=null && data.data.length){
					//ids.append('<option value="" checked>-请选择-</option>');
					var result=data.data;
			        for(var i=0;i<result.length;i++){			        	
			        	if(result[i].children&&result[i].children.length){			        		
			        		ids.append('<optgroup label="'+result[i].label+'">')
			        		var children=result[i].children;
			        		var value=result[i].value;
			        		for(var j=0;j<children.length;j++){
			        			ids.append('<option value="'+value+','+children[j].value+'">'+children[j].label+'</option>')
			        		}
			        		ids.append('</optgroup>')
			        	}else{
			        		ids.append('<option value="'+result[i].value+'">'+result[i].label+'</option>')
			        	}		            
			        }
				}
			}else{
				//ids.append("<option value='' checked>-请选择-</option>");
			}
			while(n>=length){	
				if(length!="0"&&func){
					func();
					break;
				}else{
					break;
				}	
			}
	    });
		
	}
}
//layui多级联动下拉框
function selectOnload2(settings){
    var $form;
    var form;
    var $;
    layui.use(['jquery', 'form'], function() {
        $ = layui.jquery;
        form = layui.form;
        $form = $('form');
    });
	var defaultSetting = {
			json:{},//
			func:"",
			length:0//json长度
	};
	$.extend(defaultSetting,settings);
	var json = defaultSetting.json,
		func = defaultSetting.func,
		length = defaultSetting.length;
	
	var n = 0;
	for(var i=0;i<json.length;i++){// id:val
		selectEva(json[i].name,json[i].code,json[i].value);
	}
	function selectEva(name,code,value){
		var init = function() {
			$.get("/admin/dic/"+code, function(data) {		
				if(data.code=="200"){
					n++;
					var result=data.data;
					loadSelect(result,name);
					if(value){
						var filter=name;
						var resultdata=result;
						var selectValue=value.split(",");
						var i=0;
						while(i<selectValue.length){
							if(resultdata!=null){
								$('select[name='+filter+']').val(selectValue[i]);
								filter=filter.substring(0,filter.length-1)+(parseInt(filter.substring(filter.length-1,filter.length))+1); 			
								resultdata=getData(resultdata,selectValue[i]);
								if(resultdata&&resultdata.length>0){
									loadSelect(resultdata,filter);
								}
							}
							i++;
						}
						form.render('select');
					}
				}
				while(n>=length){	
					if(length!="0"&&func){
						func();
						break;
					}else{
						break;
					}	
				}
			})
		};
		init();
		var getData=function(data,value){
			for (var i = 0; i < data.length; i++) {
				if(data[i].value==value){
					return data[i].children;
				}
			}
			return null;
		}
		//加载数据
		var loadSelect = function(resultdata,filter) {
		       var proHtml = '';
		       proHtml='<option value="">请选择</option>';
		       for (var i = 0; i < resultdata.length; i++) {
		           proHtml += '<option index="'+i+'" count="'+(resultdata[i].children==""?0:resultdata[i].children.length)+'" value="' + resultdata[i].value + '">' + resultdata[i].label + '</option>';
		       }
		       //初始化数据
		       $form.find('select[name='+filter+']').html('');
		       $form.find('select[name='+filter+']').append(proHtml);
		       form.render('select');
		       onSelect(resultdata,filter);
		      
		};
		var onSelect=function(resultdata,filter){
		   	 form.on('select('+filter+')', function(data) {
		   		 var select=data.elem.getAttribute("lay-filter");
		   		 var option=$(data.elem).find("option:selected");
		            var count = option.attr("count");
		            var index = option.attr("index");
		            select=select.substring(0,select.length-1)+(parseInt(select.substring(select.length-1,select.length))+1); 
		            if (count!='undefined'&&count > 0) {              	               	
		            	loadSelect(resultdata[index].children,select);
		            	while(true){
			            	select=select.substring(0,select.length-1)+(parseInt(select.substring(select.length-1,select.length))+1); 
			            	var nextselect = $form.find('select[name='+select+']');
			            	if(nextselect.length&&nextselect.length>0){
			           			nextselect.html('<option value="">请选择</option>');
			           			nextselect=nextselect.attr("lay-filter");
			           		} else{			           			
			           			break;
			           		}
		            	}
		            	
		            } else {
			           	 while(true){
			           		var nextselect = $form.find('select[name='+select+']');
			           		if(nextselect.length&&nextselect.length>0){
			           			nextselect.html('<option value="">请选择</option>');
			           			nextselect=nextselect.attr("lay-filter");
			           			select=nextselect.substring(0,nextselect.length-1)+(parseInt(nextselect.substring(nextselect.length-1,nextselect.length))+1); 
			           		} else{
			           			break;
			           		}
			           	 }
		           	 
		            }
		            form.render('select');
		       });
		};
		
	}	
    
}
var yunSetVal = (function(func) {
	
	//初始化函数
	var init = function(dataUrl,collback) {
		if(ifnull(dataUrl)) return false;
		$.get(dataUrl, function(data) {		
			if(data.code=="200"){
				var result=data.data;
				setVal(result);
				if(collback){
					collback();
				}				
			}			
		})
	}
	
	//判空函数
	var ifnull = function(code) {
		if(code instanceof Array) {
			if(code.length == 0) {
				return true;
			}
		} else if(code instanceof Object) {
			if(!code) {
				return true;
			}
		} else {
			if(code == 'undefined' || code == undefined || code == 'null' || code == null) {
				return true;
			}
		}
		return false;

	};
	//赋值值
	var setVal = function(data) {
		for(var i = 0; i < data.length; i++) {
			var obj = $("#"+data[i].id);
			if(ifnull(obj)) continue;
			//值赋值
			if(!ifnull(data[i].value)) {
				var type=Object.prototype.toString.call(data[i].value);
				if(type=='[object Array]'){
					obj.text(JSON.stringify(data[i].value));
				}else if(type=='[object Object]'){
					var objdata=data[i].value;
					for(var p in objdata) {
						var childobj=$("#"+p);
						if(ifnull(childobj)) continue;
						childobj.text(objdata[p]);
					}
				}else{
					obj.text(data[i].value);
				}
				
			}
		}
	}
	return {
		init: init,
        ifnull:ifnull
	}
})();
//判断是否为空
function isEmpty(code) {
	if(code instanceof Array) {
		if(code.length == 0) {
			return true;
		}
	} else if(code instanceof Object) {
		if(!code) {
			return true;
		}
	} else {
		if(code == 'undefined' || code == undefined || code == 'null' || code == null) {
			return true;
		}
	}
	return false;

};


function doubleConvertToChineseUppers(num){
    if (!/^\d*(\.\d*)?$/.test(num)) {
        return "Number is wrong!";
    }
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
    var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
            case 0:
                re = BB[7] + re;
                break;
            case 4:
                if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
                    re = BB[4] + re;
                break;
            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k = 0;
                break;
        }
        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
        if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }

    if (a.length > 1) //加上小数部分(如果有小数部分)
    {
        re += BB[6];
        for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
    }
    return re;
}
//身份证校验
function IdentityCodeValid(code) { 
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;
    ///^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
    if(!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)){
        tip = "身份证号格式错误";
        pass = false;
    }
    
   else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = false;
    }
    else{
        //18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    if(!pass);
    return pass;
}